<template>
  <div class="mengli-all-order min-fill-page">
    <div style="position:relative;margin-bottom:16px;">
      <FilterTool
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
      <div class="opeator-bar">
        <createBtn v-if="hasRouteAuth('mengli:emojiOrder:create') || isAdmin" style="margin-right:14px;" @click.native="toCreate" />
        <btnGroup
          v-if="hasRouteAuth('mengli:emojiOrder:export') || isAdmin"
          ref="btnGroupRef"
          :list="[{
            label:'导出',exportApi:'/admin/mengli/emoji/list/export', exportName:'营销授权列表', beforeExport: exportBeforeExport, type: 'export'
          }]"
        />
      </div>
    </div>
    <div v-loading="listLoading" style="min-height: 100px;">
      <u-table
        v-if="list.items.length > 0"
        ref="allOrderTableRef"
        :data="list.items"
        :row-class-name="tableRowClassName"
        :height="setTableHeight"
        :row-height="rowHeight()"
        :border="false"
        use-virtual
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @select="selectTable"
        @select-all="selectTable"
        @sort-change="sortMethod">
        <!-- <u-table-column align="left" label="订单类型" width="120">
            <template slot-scope="scope">
              <div>{{ scope.row.orderType | mengliOrderStatus }}</div>
            </template>
          </u-table-column> -->
        <u-table-column align="center" type="selection" width="50" fixed="left" />
        <u-table-column align="left" label="订单编号" width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.orderNum" is-can-click @handelClick="toDetail(scope.row)" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="含税金额(元)" min-width="130" sortable="custom" prop="taxAmount">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="成本(元)" width="120" sortable="custom" prop="costNote">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.costNote" :price="scope.row.costNote / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="IP授权费(元)" width="130" sortable="custom" prop="licensePrice">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.licensePrice" :price="scope.row.licensePrice / 100" />
          </template>
        </u-table-column>
        <!-- <u-table-column align="left" label="创意物料费" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.materielPrice || scope.row.materielPrice === 0">{{ (scope.row.materielPrice / 100) | moneyFilter }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column> -->
        <u-table-column align="left" label="客户名称" min-width="220">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.clientName" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="标签" width="150">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.tag" type="arr" label-key="name" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="销售" min-width="110">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.market"/>
          </template>
        </u-table-column>
        <u-table-column align="left" label="交付时间" width="110" sortable="custom" prop="deliveryTime">
          <template slot-scope="scope">
            {{ scope.row.deliveryTime | format('YYYY/MM/DD') }}
          </template>
        </u-table-column>
        <u-table-column align="left" label="备注" min-width="130">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.remark"/>
          </template>
        </u-table-column>
        <u-table-column align="left" label="IP形象" width="200">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.ipInfo"/>
          </template>
        </u-table-column>
        <u-table-column align="left" label="下单日期" width="110" sortable="custom" prop="orderTime">
          <template slot-scope="scope">
            {{ scope.row.orderTime | format('YYYY/MM/DD') }}
          </template>
        </u-table-column>
        <u-table-column align="left" label="创建时间" width="140" sortable="custom" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}
          </template>
        </u-table-column>
        <u-table-column :width="(hasRouteAuth('mengli:emojiOrder:edit') || hasRouteAuth('mengli:emojiOrder:delete'))?110:80" align="left" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row)"><span style="font-size:14px;">查看</span></el-button>
            <el-dropdown v-if="hasRouteAuth('mengli:emojiOrder:edit') || hasRouteAuth('mengli:emojiOrder:delete')">
              <div class="el-dropdown-link">
                <el-button type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
              </div>
              <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                <el-dropdown-item v-if="hasRouteAuth('mengli:emojiOrder:edit') || isAdmin" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('mengli:emojiOrder:delete') || isAdmin" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                  <div>删除</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else style="margin-bottom: 24px" />
    </div>
    <fixed-pagination v-if="list && list.total > 0">
      <span style="flex:1;"/>
      <el-pagination
        v-show="list.total > 0"
        :current-page="page"
        :page-size="perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </fixed-pagination>
  </div>
</template>
<script>
import setting from '@/assets/setting.png';
import FilterTool from '@/components/Tool/filter';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
// api
import { getmengliEmoji, mengliOrderDel } from '@/api/mengli';
import { getTagAll } from '@/api/config';
// tool
import { TAG_MODULES } from '@/utils/const';
import { mengliOrderStatus } from '@/filters/status';
import { format } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';

export default {
  components: { FilterTool, EmptyPlaceholder, Title, createBtn, btnGroup },
  filters: { mengliOrderStatus, format, moneyFilter },
  mixins: [tableSelections, TableAdaptive],
  data() {
    return {
      TAG_MODULES,
      setting,
      page: 1,
      perPage: 20,
      listLoading: false,
      paramsObj: {},
      list: {
        items: [],
        total: 0,
        isInint: true
      },
      tableRefName: 'allOrderTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      rangeKeyArr: [{
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }, {
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time'
      }, {
        attr: 'incomeTime',
        start: 'incomeStartTime',
        end: 'incomeEndTime',
        type: 'time'
      }],
      tagTreeList: [],
      sortType: '',
      sortName: '',
      isUmyTable: true
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    filterList() {
      return [
        { keyword: 'orderNum', name: '订单编号', type: 'input', labelWidth: '70px' },
        { keyword: 'clientName', name: '客户名称', type: 'input', labelWidth: '70px' },
        { keyword: 'market', name: '销售', type: 'input', labelWidth: '70px' },
        { keyword: 'ipFigure', name: 'IP形象', type: 'input', labelWidth: '70px' },
        { keyword: 'ipSeries', name: 'IP系列', type: 'input', labelWidth: '70px' },
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate', labelWidth: '70px' },
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate', labelWidth: '70px' },
        { keyword: 'incomeTime', name: '收入日期', timeType: 'daterange', labelWidth: '70px', type: 'rangeDate' },
        { keyword: 'tag', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        }
      ];
    }
  },
  created() {
    this.fetchData(true);
    this.queryTagTreeList();
  },
  methods: {
    hasRouteAuth,
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      /* if (params.orderTime && params.orderTime.length === 2) {
        params.orderStartTime = Math.round(params.orderTime[0] / 1000);
        params.orderEndTime = Math.round(params.orderTime[1] / 1000);
      }
      if (params.createTime && params.createTime.length === 2) {
        params.createStartTime = Math.round(params.createTime[0] / 1000);
        params.createEndTime = Math.round(params.createTime[1] / 1000);
      }
      if (params.incomeTime && params.incomeTime.length === 2) {
        params.incomeStartTime = Math.round(params.incomeTime[0] / 1000);
        params.incomeEndTime = Math.round(params.incomeTime[1] / 1000);
      }
      delete params.orderTime;
      delete params.createTime;
      delete params.incomeTime; */
      paramsRangeFormat(this.rangeKeyArr, params);
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      if (params.tag && params.tag.length > 0) {
        params.tag = params.tag.join(',');
      }
      params.page = this.page;
      params.perPage = this.perPage;
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.listLoading = true;
      getmengliEmoji(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          if (res.data.items) {
            res.data.items.forEach(i => {
              if (i.ipAry) {
                const ip = [];
                i.ipAry.forEach(j => {
                  const name = `${j.ipFigure || '--'}/${j.ipSeries || '--'}`;
                  ip.push(name);
                });
                i.ipInfo = ip.join(',');
              }
            });
          }
          this.list = res.data;
          this.setSelectRow && this.setSelectRow(res.data.items);
        }
      }).catch(e => {
        this.listLoading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    // 查询
    queryClick() {
      this.fetchData(true);
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    // 操作
    toCreate() {
      this.$router.push({
        name: 'mengliOrderAdd',
        query: { type: 1 }
      });
    },
    toDetail(item) {
      this.$router.push({
        name: 'mengliOrderDetail',
        params: { id: item.id },
        query: { type: 1 }
      });
    },
    toEdit(item) {
      this.$router.push({
        name: 'mengliOrderEdit',
        params: { id: item.id },
        query: { type: 1 }
      });
    },
    toDel(item) {
      this.$confirm('是否确定删除该订单', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        mengliOrderDel(item.id).then(res => {
          this.$message.success('删除成功');
          this.fetchData(true);
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return false;
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.MARKET_AUTH };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 导出
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(item => item.id).join(',');
      }
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
    }
  }
};
</script>
<style lang="scss" scoped>
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.mengli-all-order {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
  .order-num {
    color: #406EFF;
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
</style>
